<template>
    <el-dialog v-model="dialogVisible" @close="handleClose" :title="dialogTitle" width="95%" >

        <div class="header-controls">
          <el-input v-model="studyInstanceUid" placeholder="请输入检查实例UID" style="width: 300px; margin-right: 10px;"
            disabled />
          <el-select v-model="seriesInstanceUid" placeholder="请选择序列实例" style="width: 300px; margin-right: 10px;">
            <el-option v-for="series in seriesInstanceUidOptions" :key="series.seriseId"
              :label="series.seriseId" :value="series.seriseId" />
          </el-select>

          <el-button type="primary" @click="loadDicomViewer" >
            加载影像
          </el-button>
        </div>

        <!-- DICOM图像显示区域 -->
        <div id="dicom-viewport" class="viewport"></div>
      
    </el-dialog>
</template>

<script setup>

import { getSeriseAllList } from "@/api/pacs/serise/serise"
import { DicomDataService } from '@/api/pacs/dicom/dicomService.js'
import {getSeriesImages} from '@/api/pacs/dicom/dicom.js'
import {
  createQiniuImageIds
} from "@/utils/dicom/dicom";

import {
    createImageIdsAndCacheMetaData,
    initLib,
    initRenderingEngine,
    loadAndViewDcmFiles,
    enableStackPrefetch,
    initTools
} from '@/utils/dicom/cornerstoneCtrl'

import {
  Enums as csEnums,
  RenderingEngine,
  imageLoader,
  metaData,
  EVENTS,
  getRenderingEngine,
  init as coreInit
} from '@cornerstonejs/core'

import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'
import { nextTick } from "vue";



// 创建DicomDataService实例
const dicomService = new DicomDataService();

const { proxy } = getCurrentInstance()

// 接收父组件传递的属性
const props = defineProps({
  // 是否显示对话框
  modelValue: {
    type: Boolean,
    default: false
  },

  // 对话框标题
  title: {
    type: String,
    default: 'DICOM 医学影像查看器'
  },

  // 初始检查实例ID
  initialStudyId: {
    type: Number,
    default: null,
  },
  // 初始检查实例UID
  initialStudyUid: {
    type: String,
    default: ''
  }

})

// 定义 emits 
const emit = defineEmits(['update:modelValue', 'close'])

//dialog 是否显示(使用V-model)
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => {
    emit('update:modelValue', value)
  }
})

//dialog 的标题
const dialogTitle = computed(() => props.title)


const studyId = ref(props.initialStudyId) //studyID
const studyInstanceUid = ref(props.initialStudyUid)  //studyUId
const seriesInstanceUid = ref('') //Series UID
const seriesInstanceUidOptions = ref([])

// 视图DOM引用
const viewportRef = ref(null)

/***
 *  ViewPort 和 renderingEngine
 */

let viewportId = 'CT_STACK'
let renderingEngineId = 'myRenderingEngine'
let viewPort = null
let renderingEngine = null



// 监听props变化，当对话框打开/关闭时执行相应操作
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    // 对话框打开时，重置数据
    studyId.value = props.initialStudyId
    studyInstanceUid.value = props.initialStudyUid
    
    // 延迟一下确保DOM渲染完成
    setTimeout(() => {
      if (studyInstanceUid.value && studyInstanceUid.value.trim() !== '') {
        initDicom(); //初始化
        fetchSeriesList();
      }
    }, 100)

  }
})


// 关闭对话框Dialog
const handleClose = () => {
  dialogVisible.value = false

  emit('close')
}


/***
 * 通过StudyId，获取序列列表
*/
const fetchSeriesList = async () => {
  if (!studyInstanceUid.value.trim()) {
    proxy.$modal.msgWarning('请输入检查实例UID')
    return
  }

  if (!isValidUID(studyInstanceUid.value)) {
    proxy.$modal.msgWarning('检查实例UID格式不正确')
    return
  }

  seriesInstanceUidOptions.value = [] //为了方便遍历
  seriesInstanceUid.value = ''

  try {
    // 调用后端API获取序列列表
    const response = await getSeriseAllList({studyId: studyId.value})
    seriesInstanceUidOptions.value = response.data || []

    if (seriesInstanceUidOptions.value.length === 0) {
      proxy.$modal.msgWarning('该检查下没有找到序列数据')
    } else {
      proxy.$modal.msgSuccess(`找到 ${seriesInstanceUidOptions.value.length} 个序列`)
    }
  } catch (e) {

    proxy.$modal.msgError('获取序列列表失败: ' + error.message)
  }
}

/***
 * 显示Dicom图像
 */

const loadDicomViewer = async () => {

    // initDicom(); //初始化
    //判断是否为空
    if (!studyInstanceUid.value.trim() || !seriesInstanceUid.value.trim()) {
        proxy.$modal.msgWarning('请输入检查实例UID和序列实例UID')
        return
    }

    // 验证输入的UID格式
    if (!isValidUID(studyInstanceUid.value) || !isValidUID(seriesInstanceUid.value)) {
        proxy.$modal.msgError('UID格式不正确，请检查输入')
    }

    const series = await getSeriesImages(studyId.value, seriesInstanceUid.value);
 
    const imageIds = series.data.images;
   
      //把imageIds 进行协议封装
    const _imageIds=createQiniuImageIds(imageIds);
    console.log("=====开始加载====")
    //注册七牛云加载器
    registerQiniuImageLoader();

    console.log("输出引擎",renderingEngine);
  
    const tempViewPort = renderingEngine.getViewport(viewportId);
    
    await tempViewPort.setStack(_imageIds);
    tempViewPort.render();

    try {
        proxy.$modal.msgSuccess('开始加载DICOM影像...')
    } catch (e) {
      
        proxy.$modal.msgError('加载失败: ' + e.message)
    }

}



/**
 * 注册七牛云图像加载器
 */
function registerQiniuImageLoader() {
  // try {
  //   imageLoader.unregisterImageLoader('qiniu');
  // } catch (e) {
  //   // 忽略错误

  // }
  
  imageLoader.registerImageLoader('qiniu', (imageId) => {
    const loadPromise = new Promise(async (resolve, reject) => {
      try {
        const url = imageId.replace('qiniu:', '');
        
        if (!url || url === 'qiniu:') {
          throw new Error('无效的图像URL: ' + url);
        }

        console.log('开始加载七牛云图像:', url);
        const arrayBuffer = await dicomService.fetchDicomDataFromQiniu(url);

        if (!arrayBuffer || arrayBuffer.byteLength === 0) {
          throw new Error('下载的DICOM数据为空或大小为0');
        }

     

        // 使用wadouri加载器
        const blob = new Blob([arrayBuffer], { type: 'application/dicom' });
        const blobUrl = URL.createObjectURL(blob);
        const tempImageId = `wadouri:${blobUrl}`;
        
        console.log('使用wadouri加载器，临时imageId:', tempImageId);
        
        try {
          const dicomImageLoader = cornerstoneDICOMImageLoader.wadouri.loadImage;
          console.log(tempImageId);
          const imageLoadObject=dicomImageLoader(tempImageId);

          console.log("imageLoadObject",imageLoadObject);
          console.log("=====加载中=====");
          const image = await imageLoadObject.promise;

          console.log('通过wadouri加载器加载成功');
          console.log(image);
          
          URL.revokeObjectURL(blobUrl);
          // resolve(image);
          return image;
        } catch (wadoError) {
          console.log("========11==加载失败=====");
          console.error('wadouri加载器失败:', wadoError);
          URL.revokeObjectURL(blobUrl);
          reject(wadoError);
        }

      } catch (error) {
        console.error('七牛云图像加载失败:', error);
        reject(error);
      }
    });

    return {
      promise: loadPromise,
      cancelFn: () => {
        console.log('取消图像加载');
      }
    };
  });
}
/**
 * 初始化组件
 */
const initDicom=async()=>{
    viewportRef.value=document.getElementById("dicom-viewport");
    
    // 检查DOM元素
    if (!viewportRef.value) {
        console.log("Viewport DOM 元素未找到");
        throw new Error('Viewport DOM 元素未找到')
    }

    // 1，初始化库（必备的）
    // await initLib();
    console.log("====初始化开始====");

    await coreInit();
    await cornerstoneDICOMImageLoader.init();

    const tempRenderingEngine = new RenderingEngine(renderingEngineId);

    const viewportInput = {
      viewportId,
      element:viewportRef.value,
      type: csEnums.ViewportType.STACK,
    };

    
    tempRenderingEngine.enableElement(viewportInput);

    renderingEngine=tempRenderingEngine;
    console.log("====初始化完成====")
    // 2，初始化渲染引擎
    // const res = initRenderingEngine({
    //     element: viewportRef.value,
    //     renderingEngineId,
    //     viewportId
    // })
    
   

}

// 验证UID格式
const isValidUID = (uid) => {
  // DICOM UID格式验证：数字和点组成，长度不超过64字符
  const uidPattern = /^[0-9.]+$/
  return uidPattern.test(uid) && uid.length <= 64 && uid.length > 0
}

/**
 * 挂载
 */
onMounted(async () => {
    // 等待Dom 更新完成再 执行
    await nextTick();
   
   
})
</script>
<style scoped>
  .viewport {
            width: 800px;
            height: 800px;
          
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: black !important;
        }
</style>